﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Cci.MutableCodeModel;
using Microsoft.Cci;

using Mutable = Microsoft.Cci.MutableCodeModel;
using Ast = Microsoft.Cci.Ast;

namespace ReactiveLang.AssemblyRewriter
{
    using Statement = Microsoft.Cci.MutableCodeModel.Statement;
    using Microsoft.Cci.ILToCodeModel;
    using System.Diagnostics.Contracts;

    class ReactiveCodeMutator: CodeMutator
    {
        ReactiveMethodRewriter _methodRewriter;

        public ReactiveCodeMutator(IMetadataHost host, PdbReader pdb)
            :base(host, pdb)
        {
            Contract.Requires(host != null && pdb != null);
            _methodRewriter = new ReactiveMethodRewriter(host, pdb);
        }

        public override MethodDefinition Visit(MethodDefinition methodDefinition)
        {
            bool isReactive = methodDefinition.Attributes.Select(a => a.Type).OfType<INamespaceTypeReference>()
                .Any(t => t.Name.Value == typeof(ReactiveAttribute).Name 
                    && t.ContainingUnitNamespace.ResolvedUnitNamespace.Name.Value == typeof(ReactiveAttribute).Namespace);

            if (isReactive)
                return _methodRewriter.Visit(methodDefinition);
            else
                return base.Visit(methodDefinition);
        }
    }
}
